package com.sunk.ytmall.utils;

import com.sunk.ytmall.enums.RedisKeyEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Sunk 673116067@qq.com
 * @Date: 2018/4/18 17:04
 * @Description:
 */
@Service
public class RedisService<T> {
    @Autowired
    protected RedisTemplate<String, Object> redisTemplate;
    @Resource
    protected HashOperations<String, String, T> hashOperations;


    /**
     * 添加
     *
     * @param key    key
     * @param doamin 对象
     * @param expire 过期时间(单位:秒),传入 -1 时表示不设置过期时间
     */
    public void putHash(String key, T doamin, long expire,String rediskey) {
        hashOperations.put(rediskey, key, doamin);
        if (expire != -1) {
            redisTemplate.expire(rediskey, expire, TimeUnit.SECONDS);
        }
    }

    /**
     * 删除
     *
     * @param key 传入key的名称
     */
    public void removeHash(String key,String rediskey) {
        hashOperations.delete(rediskey, key);
    }

    /**
     * 查询
     *
     * @param key 查询的key
     * @return
     */
    public T getHash(String key,String rediskey) {
        return hashOperations.get(rediskey, key);
    }

    /**
     * 获取当前redis库下所有对象
     *
     * @return
     */
    public List<T> getHashAll(String rediskey) {
        return hashOperations.values(rediskey);
    }

    /**
     * 查询查询当前redis库下所有key
     *
     * @return
     */
    public Set<String> getHashKeys(String rediskey) {
        return hashOperations.keys(rediskey);
    }

    /**
     * 判断key是否存在redis中
     *
     * @param key 传入key的名称
     * @return
     */
    public boolean isKeyExistsInHash(String key,String rediskey) {
        return hashOperations.hasKey(rediskey, key);
    }

    /**
     * 查询当前key下缓存数量
     *
     * @return
     */
    public long getCountHash(String rediskey) {
        return hashOperations.size(rediskey);
    }

    /**
     * 清空redis
     */
    public void emptyHash(String rediskey) {
        Set<String> set = hashOperations.keys(rediskey);
        set.stream().forEach(key -> hashOperations.delete(rediskey, key));
    }
}
